<template>
  <a-modal
    v-model:visible="visible"
    @before-ok="handleOk"
    @cancel="handleCancel"
  >
    <template #title>更新</template>
    <a-form ref="formRef" :model="formData" auto-label-width>
      <a-form-item
        field="title"
        label="标题"
        :rules="[{ required: true, message: '请输入' }]"
      >
        <a-input
          v-model="formData.title"
          :maxlength="10"
          placeholder="请输入"
        />
      </a-form-item>
      <a-form-item field="content" label="简介">
        <a-textarea
          v-model="formData.content"
          :maxlength="20"
          placeholder="请输入"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { updateAnnouncementUsingPost } from '@/service/backend/announcementController.ts';
import { Message } from '@arco-design/web-vue';
import { ref } from 'vue';
import { SelectOptionData } from '@arco-design/web-vue/es/select/interface';
import useLoading from '@/hooks/useLoading';

const emit = defineEmits(['cancel', 'ok']);

const { loading, setLoading } = useLoading();
const visible = ref(false);
const formData = ref<API.AnnouncementUpdateRequest>({
  title: '',
  content: ''
});
const formRef = ref();
/**
 * @en-US Update node
 * @zh-CN 添加节点
 */
const handleUpdate = async () => {
  if (loading.value) return;
  try {
    await updateAnnouncementUsingPost(formData.value);
    Message.success('更新成功');
    return true;
  } catch (error: any) {
    Message.error(`更新失败,${error.message}`);
    return false;
  }
};

const open = (row: API.AnnouncementVO) => {
  formData.value = row;
  visible.value = true;
};

const handleOk = async done => {
  try {
    const error = await formRef.value.validate();
    if (!error) {
      await handleUpdate(); // 提交数据
      done(true); // 关闭 Modal
      formRef.value?.resetFields();
      emit('ok');
    } else {
      done(false); // 阻止 Modal 关闭
    }
  } catch (e) {
    Message.error(e.message);
    done(false);
  }
};

function handleCancel() {
  formRef.value?.resetFields();
  emit('cancel');
}

defineExpose({
  open
});
</script>

<style scoped lang="less"></style>
